from flask import Flask, request, render_template
from flask_socketio import SocketIO, join_room, leave_room, emit
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, engineio_logger=True, async_mode='threading')

# 房间管理
rooms = {}


@app.route('/')
def index():
    return "Server is running!"


@socketio.on('connect')
def handle_connect():
    logger.info(f'客户端连接: {request.sid}')
    emit('connectionSuccess')


@socketio.on('disconnect')
def handle_disconnect():
    logger.info(f'客户端断开连接: {request.sid}')
    # 清理房间中的用户
    for room in rooms:
        if request.sid in rooms[room]:
            rooms[room].remove(request.sid)
            if not rooms[room]:  # 如果房间为空
                del rooms[room]
            emit('userLeft', {'sid': request.sid}, room=room)
            break


@socketio.on('joinRoom')
def handle_join_room(roomId):
    logger.info(f'用户 {request.sid} 加入房间 {roomId}')
    join_room(roomId)

    # 更新房间信息
    if roomId not in rooms:
        rooms[roomId] = []
    rooms[roomId].append(request.sid)

    emit('roomJoined', {'roomId': roomId, 'members': len(rooms[roomId])})


@socketio.on('callRemote')
def handle_call_remote(roomId):
    logger.info(f'房间 {roomId} 收到呼叫请求')
    emit('callRemote', room=roomId, skip_sid=request.sid)


@socketio.on('acceptCall')
def handle_accept_call(roomId):
    logger.info(f'房间 {roomId} 有用户接受呼叫')
    emit('acceptCall', room=roomId, skip_sid=request.sid)


@socketio.on('sendOffer')
def handle_send_offer(data):
    roomId = data['roomId']
    offer = data['offer']
    logger.info(f'转发Offer到房间 {roomId}')
    emit('sendOffer', offer, room=roomId, skip_sid=request.sid)


@socketio.on('sendAnswer')
def handle_send_answer(data):
    roomId = data['roomId']
    answer = data['answer']
    logger.info(f'转发Answer到房间 {roomId}')
    emit('sendAnswer', answer, room=roomId, skip_sid=request.sid)


@socketio.on('sendCandidate')
def handle_send_candidate(data):
    roomId = data['roomId']
    candidate = data['candidate']
    logger.info(f'转发候选到房间 {roomId}: {candidate["candidate"]}')  # 关键日志
    emit('sendCandidate', candidate, room=roomId, skip_sid=request.sid)


@socketio.on('hangUp')
def handle_hang_up(roomId):
    logger.info(f'房间 {roomId} 挂断通话')
    emit('hangUp', room=roomId)


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True, allow_unsafe_werkzeug=True, ssl_context=('cert.pem', 'key.pem'))
